<template>
  <div class="add-to-cart">
    <el-input-number 
      v-model="quantity" 
      :min="1" 
      :max="99" 
      size="small"
      class="quantity-input"
    />
    <el-button 
      type="primary" 
      :icon="Plus" 
      @click="addToCart"
      :loading="loading"
    >
      加入购物车
    </el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useCartStore } from '../store/cartStore'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  product: {
    type: Object,
    required: true
  }
})

const cartStore = useCartStore()
const quantity = ref(1)
const loading = ref(false)

const addToCart = () => {
  loading.value = true
  
  // 模拟网络延迟
  setTimeout(() => {
    try {
      // 添加指定数量的商品
      for (let i = 0; i < quantity.value; i++) {
        cartStore.addToCart(props.product)
      }
      
      ElMessage({
        type: 'success',
        message: `已将 ${quantity.value} 件 ${props.product.name} 加入购物车`
      })
      
      // 重置数量
      quantity.value = 1
    } catch (error) {
      ElMessage.error('添加到购物车失败，请重试')
      console.error('添加到购物车失败:', error)
    } finally {
      loading.value = false
    }
  }, 300)
}
</script>

<style scoped>
.add-to-cart {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 15px 0;
}

.quantity-input {
  width: 120px;
}
</style>